package furns.web;

import furns.entity.Member;
import furns.service.MemberService;
import furns.service.impl.MemberServiceImpl;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@SuppressWarnings("all")
@WebServlet(name = "RegisterServlet", urlPatterns = "/registerServlet")
public class RegisterServlet extends HttpServlet {
    //创建一个memberService对象,便于调用其方法
    private MemberService memberService = new MemberServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        System.out.println("RegisterServlet被调用");
        //接收用户输入的注册信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        //判断用户名是否可用
        if (!memberService.isExistsUsername(username)) { //表示用户名可用，然后进行后续注册
//            System.out.println("用户名" + username + "可用");
            //构建一个member对象用于封装注册信息
            Member member = new Member(null, username, password, email);
            if (memberService.registerMember(member)) {
                //注册成功后，转发到指定页面。
                //路径中的第一个 / 会被服务器解析成 http://ip:port/工程名/
                request.getRequestDispatcher("/views/member/register_ok.jsp").forward(request, response);
            } else {
                //注册失败后，转发到指定页面
                request.getRequestDispatcher("/views/member/register_fail.jsp").forward(request, response);
            }
        } else { //表示用户名不可用
//            System.out.println("用户名" + username + "不可用");
            //跳转到登录页面，后续添加 提示用户名不可用
            request.getRequestDispatcher("/views/member/login.jsp").forward(request, response);
        }
    }
}